package com.learning.servlet2x.filter.gzip;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

/**
 * ClassName: GzipResponseWrapper
 * Description: 封装的 Response, 不会真正输出到客户端
 * 继承 HttpServletResponseWrapper，其实现了 HttpServletResponse 接口
 * Date: 2014-12-9 21:41 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class GzipResponseWrapper extends HttpServletResponseWrapper {

    /**
     * 默认的 response
     */
    private HttpServletResponse response;

    /**
     * 自定义的 outputStream, 执行close()的时候对数据压缩，并输出
     */
    private GzipOutputStream gzipOutputStream;

    /**
     * 自定义 printWriter，将内容输出到 GZipOutputStream 中
     */
    private PrintWriter writer;

    public GzipResponseWrapper(HttpServletResponse response) {
        super(response);
        this.response = response;
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        if (gzipOutputStream == null) {
            gzipOutputStream = new GzipOutputStream(response);
        }
        return gzipOutputStream;
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        if (writer == null) {
            writer = new PrintWriter(new OutputStreamWriter(new GzipOutputStream(response), "UTF-8"));
        }
        return writer;
    }

    /**
     * 压缩后数据长度会发生变化 因此将该方法内容置空
     *
     * @param contentLength
     */
    @Override
    public void setContentLength(int contentLength) {
    }

    @Override
    public void flushBuffer() throws IOException {
        gzipOutputStream.flush();
    }

    public void finishResponse() throws IOException {
        if (gzipOutputStream != null) {
            gzipOutputStream.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}
